package com.css.fxfzysx.modules.vaolEngineering.service.impl;

import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.css.fxfzysx.base.response.RestResponse;
import com.css.fxfzysx.constants.FxfzConstants;
import com.css.fxfzysx.constants.YNEnum;
import com.css.fxfzysx.modules.cztDataMange.result.ParsingResult;
import com.css.fxfzysx.modules.lifeline.annotation.ValidationProcessor;
import com.css.fxfzysx.modules.lifeline.entity.newEntity.SmxMainTableEntity;
import com.css.fxfzysx.modules.lifeline.entity.newEntity.SmxVersionEntity;
import com.css.fxfzysx.modules.lifeline.entity.newEntity.SmxWaterSupplyEntity;
import com.css.fxfzysx.modules.lifeline.repository.LifelineEngineeringRepository;
import com.css.fxfzysx.modules.lifeline.utils.ShpUtils;
import com.css.fxfzysx.modules.lifeline.vo.basic.DestructiveStateVo;
import com.css.fxfzysx.modules.vaolEngineering.dto.DynamicFieldsDto;
import com.css.fxfzysx.modules.vaolEngineering.param.update.WaterSupplyParam;
import com.css.fxfzysx.modules.vaolEngineering.repository.WsfManagementRepository;
import com.css.fxfzysx.modules.vaolEngineering.service.WsfManagementService;
import com.css.fxfzysx.modules.vaolEngineering.utils.CheckUtil;
import com.css.fxfzysx.modules.vaolEngineering.utils.MainTableUtils;
import com.css.fxfzysx.modules.vaolEngineering.vo.importVo.CpweDamageImportVo;
import com.css.fxfzysx.modules.ysxManagement.entity.DynamicFieldsEntity;
import com.css.fxfzysx.modules.ysxManagement.entity.RsRatioEntity;
import com.css.fxfzysx.modules.ysxManagement.repository.WsfCoefficientRepository;
import com.css.fxfzysx.modules.ysxManagement.repository.ZqtCiRepository;
import com.css.fxfzysx.util.PlatformDateUtils;
import com.css.fxfzysx.util.PlatformObjectUtils;
import com.css.fxfzysx.util.ShpAnalyticUtil;
import com.css.fxfzysx.util.UUIDGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Slf4j
public class WsfManagementServiceImpl implements WsfManagementService {

    @Autowired
    private WsfManagementRepository wsfManagementRepository;

    @Autowired
    private ZqtCiRepository zqtCiRepository;

    @Autowired
    private WsfCoefficientRepository wsfCoefficientRepository;

    @Autowired
    private ShpUtils shpUtils;

    @Autowired
    private MainTableUtils mainTableUtils;

    @Autowired
    private LifelineEngineeringRepository lifelineEngineeringRepository;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public RestResponse calculationDamageDegree(String versionId, String tableId) {
        try {
            List<SmxWaterSupplyEntity> list = new ArrayList<>();
            if (PlatformObjectUtils.isNotEmpty(tableId)) {
                SmxWaterSupplyEntity entity = wsfManagementRepository.getByTableId(tableId);
                list.add(entity);
            } else {
                list = wsfManagementRepository.getByVersionId(versionId);
            }
            List<DynamicFieldsEntity> vList = zqtCiRepository.getDynamicFields("v与纵向受拉钢筋表面形状有关的系数");
            List<RsRatioEntity> rsRatioList = wsfCoefficientRepository.getAllRsRatio();
            Map<String, DynamicFieldsEntity> map = vList.stream().collect(
                    Collectors.toMap(DynamicFieldsEntity::getCbrsId,
                            w -> w));

            List<DynamicFieldsDto> collect = rsRatioList.stream().map(h -> {
                return toDynamicFields(map.get(h.getProjectId()), h);
            }).collect(Collectors.toList());

            if (PlatformObjectUtils.isNotEmpty(list)) {
                StringBuilder ids = new StringBuilder();
                for (SmxWaterSupplyEntity entity : list) {
                    //裂缝间钢筋应变的不均匀系数
                    BigDecimal result1 = BigDecimal.ONE
                            .subtract(BigDecimal.valueOf(0.235).multiply(BigDecimal.ONE.add(new BigDecimal(2).multiply(entity.getShapeFactor1()))
                                    .add(BigDecimal.valueOf(0.4).multiply(entity.getShapeFactor2())).multiply(entity.getRuptureStrength())
                                    .multiply(entity.getSectionWidth()).multiply(entity.getSectionHeight().pow(2))
                                    .divide(entity.getSectionBendingMoment(), 4, RoundingMode.HALF_UP)))
                            .multiply(BigDecimal.valueOf(1.2));

                    entity.setResult1(result1);
                    //eg
                    BigDecimal result2 = result1.multiply(entity.getSteelStrain()).setScale(4, RoundingMode.UP);
                    entity.setResult2(result2);

                    if (collect.stream().noneMatch(m -> m.getTitle().equals(mainTableUtils.getValueByKey("smxgsgjlx", entity.getRebarType())))) {
                        return RestResponse.fail("失败,请在 【供水设施系数维护】 模块中维护 {v与纵向受拉钢筋表面形状有关的系数} 信息");
                    }
                    collect.forEach(dto -> {
                        if (dto.getStiffenerType().equals("v") && mainTableUtils.getValueByKey("smxgsgjlx", entity.getRebarType()).equals(dto.getTitle())) {
                            entity.setResult3(dto.getValue());
                            ids.append(dto.getId());
                        }
                    });

                    //平均裂缝间距
                    BigDecimal result4 = new BigDecimal(6).add(BigDecimal.valueOf(0.06).
                            multiply(entity.getDiameterOfTensileReinforcement().divide(entity.getReinforcementRatio(), 4, RoundingMode.HALF_UP))
                            .multiply(new BigDecimal(1).add(new BigDecimal(2).multiply(entity.getShapeFactor1()))
                                    .add(BigDecimal.valueOf(0.4).multiply(entity.getShapeFactor2())))).multiply(entity.getResult3());
                    entity.setResult4(result4);

                    //钢筋的平均应变
                    BigDecimal result5 = (result2.subtract(entity.getAverageStrain())).multiply(entity.getResult3());
                    entity.setResult5(result5);

                    //刚筋截面积 Ag
                    BigDecimal result8 = new BigDecimal(Math.PI)
                            .multiply(entity.getDiameterOfTensileReinforcement().pow(2))
                            .divide(new BigDecimal(4), 10, RoundingMode.HALF_UP);
                    entity.setResult8(result8.setScale(4, RoundingMode.HALF_UP));

                    //og
                    BigDecimal multiply = BigDecimal.valueOf(0.87).multiply(result5).multiply(entity.getDistance());
                    BigDecimal result9 = entity.getSectionBendingMoment().divide(multiply, 4, RoundingMode.HALF_UP);
                    entity.setResult9(result9);

                    //ofMax
                    BigDecimal divide = result9.divide(entity.getElasticModulus(), 10, RoundingMode.HALF_UP);
                    BigDecimal result10 = BigDecimal.valueOf(2).multiply(entity.getResult1()).multiply(divide).multiply(entity.getResult4());


                    entity.setResult10(result10.setScale(4, RoundingMode.HALF_UP));

                    if (PlatformObjectUtils.isEmpty(entity.getResult10Correct())) {
                        entity.setResult10Correct(entity.getResult10());
                    }

                    //将米转换为毫米
                    BigDecimal result10mm = result10.multiply(new BigDecimal(1000));

                    //破坏程度
                    if (result10mm.compareTo(BigDecimal.valueOf(0.2)) < 0) {
                        entity.setDisasterRateState("基本完好");
                    }
                    if (result10mm.compareTo(BigDecimal.valueOf(0.2)) != -1 && result10mm.compareTo(BigDecimal.valueOf(0.5)) < 0) {
                        entity.setDisasterRateState("轻微破坏");
                    }
                    if (result10mm.compareTo(BigDecimal.valueOf(0.5)) != -1 && result10mm.compareTo(BigDecimal.valueOf(0.8)) < 0) {
                        entity.setDisasterRateState("中等破坏");
                    }
                    if (result10mm.compareTo(BigDecimal.valueOf(0.8)) != -1 && result10mm.compareTo(BigDecimal.valueOf(1.2)) < 0) {
                        entity.setDisasterRateState("严重破坏");
                    }
                    if (result10mm.compareTo(BigDecimal.valueOf(1.2)) > 0) {
                        entity.setDisasterRateState("毁坏");
                    }

                    if (PlatformObjectUtils.isNotEmpty(entity.getResult10Correct())) {
                        BigDecimal correct = entity.getResult10Correct().multiply(new BigDecimal(1000));
                        if (correct.compareTo(BigDecimal.valueOf(0.2)) < 0) {
                            entity.setDisasterRateStateCorrect("基本完好");
                        }
                        if (correct.compareTo(BigDecimal.valueOf(0.2)) != -1 && correct.compareTo(BigDecimal.valueOf(0.5)) < 0) {
                            entity.setDisasterRateStateCorrect("轻微破坏");
                        }
                        if (correct.compareTo(BigDecimal.valueOf(0.5)) != -1 && correct.compareTo(BigDecimal.valueOf(0.8)) < 0) {
                            entity.setDisasterRateStateCorrect("中等破坏");
                        }
                        if (correct.compareTo(BigDecimal.valueOf(0.8)) != -1 && correct.compareTo(BigDecimal.valueOf(1.2)) < 0) {
                            entity.setDisasterRateStateCorrect("严重破坏");
                        }
                        if (correct.compareTo(BigDecimal.valueOf(1.2)) > 0) {
                            entity.setDisasterRateStateCorrect("毁坏");
                        }
                    }
                    wsfManagementRepository.saveWaterSupplyResult(entity);
                    String year = mainTableUtils.getKeyByValue("smxjsnd", MainTableUtils.getYear(entity.getYear()));
                    DestructiveStateVo stateVo = wsfManagementRepository.getByBasicInfo(entity,year);
                    mainTableUtils.updateCalculationStatus(entity.getTableId(),stateVo.getDisasterRate6State(),stateVo.getDisasterRate7State(),stateVo.getDisasterRate8State(),stateVo.getDisasterRate9State(),stateVo.getDisasterRate10State(), 1);
                    mainTableUtils.updateModelBaseIds(ids.toString(), null, entity.getTableId());
                }
            }
            mainTableUtils.updateVersionCalculationStatus(versionId, 0);
            return RestResponse.succeed("计算成功!");
        }catch (ArithmeticException e){
            log.error(e.getMessage(),e);
            return RestResponse.fail("数据异常,被除数不可为0");
        } catch (Exception e) {
            log.error("get calculationDamageDegree error:{}", e.getMessage(), e);
            return RestResponse.fail("数据异常,计算失败!");
        }
    }

    private DynamicFieldsDto toDynamicFields(DynamicFieldsEntity dynamicFieldsEntity, RsRatioEntity h) {
        DynamicFieldsDto dto = new DynamicFieldsDto();
        dto.setId(h.getCrsrId());
        dto.setProjectId(dynamicFieldsEntity.getCbrsId());
        dto.setTitle(dynamicFieldsEntity.getInfo());
        dto.setValue(h.getRebarValue());
        dto.setStiffenerType(h.getRebarType());
        return dto;
    }

    @Override
    public RestResponse importDamageDegree(MultipartFile file) {
        try {
            ExcelReader reader = ExcelUtil.getReader(file.getInputStream());
            List<List<Object>> read = reader.read(1, reader.getRowCount());
            List<Object> title = reader.readRow(0);
            String titleName = "[b 截面宽度 (m), h 截面高度(m), Rf 混凝土抗裂强度(N/m^2), M 计算截面的弯矩（N.m）, εg裂缝截面处钢筋的应变, d 受拉钢筋直径(mm), μ 配筋率(m), r1 截面形状有关的系数, r'1 截面形状有关的系数, ν与纵向受拉钢筋表面形状有关的系数, 钢筋水平处裂缝之间受拉混凝土的平均应变, Eg钢筋的弹性模量, h0(m)配筋到惯性轴的距离]";
            if (!titleName.equals(title.toString())) {
                return RestResponse.fail("导入失败，请检查表头是否改动");
            }
            if (read.size() == 0) {
                return RestResponse.fail("导入失败，表格中无数据");
            }
            //数据校验
            RestResponse rs = CheckUtil.check(1, read.size(), read, titleName);
            if (rs.getCode() != 200) {
                return RestResponse.fail(rs.getMessage());
            }
            ArrayList<CpweDamageImportVo> dataList = new ArrayList<>();
            read.forEach(it -> {
                CpweDamageImportVo entity = new CpweDamageImportVo();
                entity.setWidth(new BigDecimal(it.get(0).toString()));
                entity.setHeight(new BigDecimal(it.get(1).toString()));
                entity.setRf(new BigDecimal(it.get(2).toString()));
                entity.setJmwj(new BigDecimal(it.get(3).toString()));
                entity.setLfjmcgjyb(new BigDecimal(it.get(4).toString()));
                entity.setDiameter(new BigDecimal(it.get(5).toString()));
                entity.setPjl(new BigDecimal(it.get(6).toString()));
                entity.setJmRatio1(new BigDecimal(it.get(7).toString()));
                entity.setJmRatio2(new BigDecimal(it.get(8).toString()));
                entity.setSurfaceRatio(new BigDecimal(it.get(9).toString()));
                entity.setSpclfzjsl(new BigDecimal(it.get(10).toString()));
                entity.setElasticModulus(new BigDecimal(it.get(11).toString()));
                entity.setDistance(new BigDecimal(it.get(12).toString()));
                dataList.add(entity);
            });
            return RestResponse.succeed(dataList);
        } catch (IOException e) {
            String errorMessage = "数据异常,导入失败!";
            log.error(errorMessage, e);
            return RestResponse.fail(errorMessage);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Map<String, Object> uploadWaterSupply(String fileIds, String versionId, String userId) throws Exception {
        Map<String, Object> map = new HashMap<>();
        shpUtils.uniformFileName(fileIds);
        ParsingResult shpData = shpUtils.getShpData(fileIds);
        //是否成功
        if (!shpData.getMessage().equals("ok")) {
            map.put("res", false);
            map.put("mess", shpData.getMessage());
        }
        List<List<Object>> shpList = shpData.getShpList();
        List<SmxWaterSupplyEntity> waterSupplyList = new ArrayList<>();
        for (int i = 0; i < shpList.size(); i++) {
            String id = UUIDGenerator.getUUID();
            List<Object> list = shpList.get(i);
            if (list.size() < 50) {
                map.put("res", false);
                return map;
            }
            SmxWaterSupplyEntity entity = new SmxWaterSupplyEntity();
            entity.setDelFlag(YNEnum.N.toString());
            entity.setId(UUIDGenerator.getUUID());
            entity.setCreateUser(userId);
            entity.setCreateTime(PlatformDateUtils.getCurrentDate());
            entity.setTableId(id);

            if (!PlatformObjectUtils.isEmpty(list.get(0))) {
                entity.setGeom(list.get(0).toString());
            }
            if (!PlatformObjectUtils.isEmpty(list.get(1))) {
                entity.setWaterSupplyId(ShpAnalyticUtil.getStringVal(list.get(1).toString(), "编码", true));
            }
            if (!PlatformObjectUtils.isEmpty(list.get(2))) {
                entity.setStyle(ShpAnalyticUtil.getStringVal(list.get(1).toString(), "结构形式", true));
            }
            if (!PlatformObjectUtils.isEmpty(list.get(3))) {
                entity.setMaterial(ShpAnalyticUtil.getStringVal(list.get(3).toString(), "结构材料", true));
            }
            if (!PlatformObjectUtils.isEmpty(list.get(4))) {
                entity.setThickness(BigDecimal.valueOf(ShpAnalyticUtil.getDoubleVal(list.get(4).toString(), "水池壁厚", true)));
            }
            if (!PlatformObjectUtils.isEmpty(list.get(5))) {
                entity.setShape(ShpAnalyticUtil.getStringVal(list.get(5).toString(), "水池形状", true));
            }
            if (!PlatformObjectUtils.isEmpty(list.get(6))) {
                entity.setRadius(BigDecimal.valueOf(ShpAnalyticUtil.getDoubleVal(list.get(6).toString(), "水池半径", true)));
            }
            if (!PlatformObjectUtils.isEmpty(list.get(7))) {
                entity.setSlength(BigDecimal.valueOf(ShpAnalyticUtil.getDoubleVal(list.get(7).toString(), "水池短边", true)));
            }
            if (!PlatformObjectUtils.isEmpty(list.get(8))) {
                entity.setLength(BigDecimal.valueOf(ShpAnalyticUtil.getDoubleVal(list.get(8).toString(), "水池长边", true)));
            }
            if (!PlatformObjectUtils.isEmpty(list.get(9))) {
                entity.setCapacity(BigDecimal.valueOf(ShpAnalyticUtil.getDoubleVal(list.get(9).toString(), "容量", true)));
            }
            if (!PlatformObjectUtils.isEmpty(list.get(10))) {
                entity.setDepth(BigDecimal.valueOf(ShpAnalyticUtil.getDoubleVal(list.get(10).toString(), "水深度", true)));
            }
            if (!PlatformObjectUtils.isEmpty(list.get(11))) {
                entity.setHeight(BigDecimal.valueOf(ShpAnalyticUtil.getDoubleVal(list.get(11).toString(), "水池高度", true)));
            }
            if (!PlatformObjectUtils.isEmpty(list.get(12))) {
                entity.setIntensity(ShpAnalyticUtil.getStringVal(list.get(12).toString(), "设防情况", true));
            }
            if (!PlatformObjectUtils.isEmpty(list.get(13))) {
                entity.setYear(ShpAnalyticUtil.getIntegerVal(list.get(13).toString(), "建设年代", true));
            }
            if (!PlatformObjectUtils.isEmpty(list.get(14))) {
                entity.setRebarType(list.get(14).toString());
            }
            if (!PlatformObjectUtils.isEmpty(list.get(15))) {
                entity.setSectionWidth(new BigDecimal(list.get(15).toString()));
            }
            if (!PlatformObjectUtils.isEmpty(list.get(16))) {
                entity.setSectionHeight(new BigDecimal(list.get(16).toString()));
            }
            if (!PlatformObjectUtils.isEmpty(list.get(17))) {
                entity.setSectionBendingMoment(new BigDecimal(list.get(17).toString()));
            }
            if (!PlatformObjectUtils.isEmpty(list.get(18))) {
                entity.setSteelStrain(new BigDecimal(list.get(18).toString()));
            }
            if (!PlatformObjectUtils.isEmpty(list.get(19))) {
                entity.setDiameterOfTensileReinforcement(new BigDecimal(list.get(19).toString()));
            }
            if (!PlatformObjectUtils.isEmpty(list.get(20))) {
                entity.setReinforcementRatio(new BigDecimal(list.get(20).toString()));
            }
            if (!PlatformObjectUtils.isEmpty(list.get(21))) {
                entity.setShapeFactor1(new BigDecimal(list.get(21).toString()));
            }
            if (!PlatformObjectUtils.isEmpty(list.get(22))) {
                entity.setShapeFactor2(new BigDecimal(list.get(22).toString()));
            }
            if (!PlatformObjectUtils.isEmpty(list.get(23))) {
                entity.setAverageStrain(new BigDecimal(list.get(23).toString()));
            }
            if (!PlatformObjectUtils.isEmpty(list.get(24))) {
                entity.setElasticModulus(new BigDecimal(list.get(24).toString()));
            }
            if (!PlatformObjectUtils.isEmpty(list.get(25))) {
                entity.setDistance(new BigDecimal(list.get(25).toString()));
            }
            if (!PlatformObjectUtils.isEmpty(list.get(26))) {
                entity.setJoint(list.get(26).toString());
            }
            if (!PlatformObjectUtils.isEmpty(list.get(27))) {
                entity.setPresent(list.get(27).toString());
            }
            if (!PlatformObjectUtils.isEmpty(list.get(28))) {
                entity.setQuality(list.get(28).toString());
            }
            if (!PlatformObjectUtils.isEmpty(list.get(29))) {
                entity.setSurfaceShape1(list.get(29).toString());
            }
            if (!PlatformObjectUtils.isEmpty(list.get(30))) {
                entity.setSurfaceShape2(list.get(30).toString());
            }
            if (!PlatformObjectUtils.isEmpty(list.get(31))) {
                entity.setDiameter1(new BigDecimal(list.get(31).toString()));
            }
            if (!PlatformObjectUtils.isEmpty(list.get(32))) {
                entity.setDiameter2(new BigDecimal(list.get(32).toString()));
            }
            if (!PlatformObjectUtils.isEmpty(list.get(33))) {
                entity.setStrengthGrade(list.get(33).toString());
            }
            if (!PlatformObjectUtils.isEmpty(list.get(34))) {
                entity.setRuptureStrength(new BigDecimal(list.get(34).toString()));
            }
            if (!PlatformObjectUtils.isEmpty(list.get(35))) {
                entity.setKinds1(list.get(35).toString());
            }
            if (!PlatformObjectUtils.isEmpty(list.get(36))) {
                entity.setKinds2(list.get(36).toString());
            }
            if (!PlatformObjectUtils.isEmpty(list.get(37))) {
                entity.setThicknessOfProtectiveLayer1(new BigDecimal(list.get(37).toString()));
            }
            if (!PlatformObjectUtils.isEmpty(list.get(38))) {
                entity.setThicknessOfProtectiveLayer2(new BigDecimal(list.get(38).toString()));
            }
            if (!PlatformObjectUtils.isEmpty(list.get(39))) {
                entity.setVerticalReinforcement1(list.get(39).toString());
            }
            if (!PlatformObjectUtils.isEmpty(list.get(40))) {
                entity.setVerticalReinforcement2(list.get(40).toString());
            }
            if (!PlatformObjectUtils.isEmpty(list.get(41))) {
                entity.setSite(list.get(41).toString());
            }
            if (!PlatformObjectUtils.isEmpty(list.get(42))) {
                entity.setLiquefaction6(list.get(42).toString());
            }
            if (!PlatformObjectUtils.isEmpty(list.get(43))) {
                entity.setLiquefaction7(list.get(43).toString());
            }
            if (!PlatformObjectUtils.isEmpty(list.get(44))) {
                entity.setLiquefaction8(list.get(44).toString());
            }
            if (!PlatformObjectUtils.isEmpty(list.get(45))) {
                entity.setLiquefaction9(list.get(45).toString());
            }
            if (!PlatformObjectUtils.isEmpty(list.get(46))) {
                entity.setLandform6(list.get(46).toString());
            }
            if (!PlatformObjectUtils.isEmpty(list.get(47))) {
                entity.setLandform7(list.get(47).toString());
            }
            if (!PlatformObjectUtils.isEmpty(list.get(48))) {
                entity.setLandform8(list.get(48).toString());
            }
            if (!PlatformObjectUtils.isEmpty(list.get(49))) {
                entity.setLandform9(list.get(49).toString());
            }
            if (!PlatformObjectUtils.isEmpty(list.get(50))) {
                entity.setLongitude(ShpAnalyticUtil.getStringVal(list.get(50).toString(), "经度", true));
            }
            if (!PlatformObjectUtils.isEmpty(list.get(51))) {
                entity.setLatitude(ShpAnalyticUtil.getStringVal(list.get(51).toString(), "纬度", true));
            }
            if (list.size() > 52 && !PlatformObjectUtils.isEmpty(list.get(52))) {
                entity.setExtends1(list.get(52).toString());
            }
            if (list.size() > 53 && !PlatformObjectUtils.isEmpty(list.get(53))) {
                entity.setExtends2(list.get(53).toString());
            }
            if (list.size() > 54 && !PlatformObjectUtils.isEmpty(list.get(54))) {
                entity.setExtends3(list.get(54).toString());
            }
            if (list.size() > 55 && !PlatformObjectUtils.isEmpty(list.get(55))) {
                entity.setExtends4(list.get(55).toString());
            }
            if (list.size() > 56 && !PlatformObjectUtils.isEmpty(list.get(56))) {
                entity.setExtends5(list.get(56).toString());
            }
            if (list.size() > 57 && !PlatformObjectUtils.isEmpty(list.get(57))) {
                entity.setExtends6(list.get(57).toString());
            }
            if (list.size() > 58 && !PlatformObjectUtils.isEmpty(list.get(58))) {
                entity.setExtends7(list.get(58).toString());
            }
            if (list.size() > 59 && !PlatformObjectUtils.isEmpty(list.get(59))) {
                entity.setExtends8(list.get(59).toString());
            }
            if (list.size() > 60 && !PlatformObjectUtils.isEmpty(list.get(60))) {
                entity.setExtends9(list.get(60).toString());
            }
            if (list.size() > 61 && !PlatformObjectUtils.isEmpty(list.get(61))) {
                entity.setExtends10(list.get(61).toString());
            }

            entity.setVersionId(versionId);
            waterSupplyList.add(entity);

            SmxMainTableEntity mainEntity = new SmxMainTableEntity();
            mainEntity.setId(id);
            mainEntity.setYear(entity.getYear());
            mainEntity.setCreateUser(userId);
            mainEntity.setVersionId(versionId);
            mainEntity.setFortification(entity.getIntensity());
            mainEntity.setBusinessObject(FxfzConstants.CZT_SMX_GS);
            mainTableUtils.saveMainTable(mainEntity);
        }
        boolean res = false;

        int i = 1;
        for (SmxWaterSupplyEntity entity : waterSupplyList) {
            entity.setSerialNumber(i);
            res = wsfManagementRepository.saveWaterSupply(entity);
            i += 1;
        }
        map.put("res", res);
        return map;
    }

    @Override
    public HashMap<Integer, ArrayList<String>> getDataValidation(String versionId) {
        HashMap<Integer, ArrayList<String>> map = new HashMap<>();
        SmxVersionEntity versionEntity = lifelineEngineeringRepository.getById(versionId);
        if (PlatformObjectUtils.isNotEmpty(versionEntity)) {
            List<SmxWaterSupplyEntity> waterSupplyList = wsfManagementRepository.getByVersionId(versionEntity.getId());
            int i = 1;
            for (SmxWaterSupplyEntity waterSupplyEntity : waterSupplyList) {
                ArrayList<String> list = ValidationProcessor.validate(waterSupplyEntity);
                if (list.size() != 0) {
                    map.put(i, list);
                }
                i += 1;
            }
        }
        return map;
    }

    @Override
    public SmxWaterSupplyEntity getByTableId(String id) {
        return wsfManagementRepository.getByTableId(id);
    }

    @Override
    public void updateWsfManagementById(WaterSupplyParam waterSupplyParam) {
        wsfManagementRepository.updateWsfManagementById(waterSupplyParam);
    }

    @Override
    public RestResponse count(WaterSupplyParam param) {

        List<DynamicFieldsEntity> vList = zqtCiRepository.getDynamicFields("v与纵向受拉钢筋表面形状有关的系数");
        List<RsRatioEntity> rsRatioList = wsfCoefficientRepository.getAllRsRatio();
        Map<String, DynamicFieldsEntity> map = vList.stream().collect(
                Collectors.toMap(DynamicFieldsEntity::getCbrsId,
                        w -> w));

        List<DynamicFieldsDto> collect = rsRatioList.stream().map(h -> {
            return toDynamicFields(map.get(h.getProjectId()), h);
        }).collect(Collectors.toList());

        StringBuilder ids = new StringBuilder();
        //裂缝间钢筋应变的不均匀系数
        BigDecimal result1 = BigDecimal.ONE
                .subtract(BigDecimal.valueOf(0.235).multiply(BigDecimal.ONE.add(new BigDecimal(2).multiply(param.getShapeFactor1()))
                        .add(BigDecimal.valueOf(0.4).multiply(param.getShapeFactor2())).multiply(param.getRuptureStrength())
                        .multiply(param.getSectionWidth()).multiply(param.getSectionHeight().pow(2))
                        .divide(param.getSectionBendingMoment(), 4, RoundingMode.HALF_UP)))
                .multiply(BigDecimal.valueOf(1.2));

        param.setResult1(result1);
        //eg
        BigDecimal result2 = result1.multiply(param.getSteelStrain()).setScale(4, RoundingMode.UP);
        param.setResult2(result2);

        if (collect.stream().noneMatch(m -> m.getTitle().equals(mainTableUtils.getValueByKey("smxgsgjlx", param.getRebarType())))) {
            return RestResponse.fail("失败,请在 【供水设施系数维护】 模块中维护 {v与纵向受拉钢筋表面形状有关的系数} 信息");
        }
        collect.forEach(dto -> {
            if (dto.getStiffenerType().equals("v") && mainTableUtils.getValueByKey("smxgsgjlx", param.getRebarType()).equals(dto.getTitle())) {
                param.setResult3(dto.getValue());
                ids.append(dto.getId());
            }
        });

        //平均裂缝间距
        BigDecimal result4 = new BigDecimal(6).add(BigDecimal.valueOf(0.06).
                multiply(param.getDiameterOfTensileReinforcement().divide(param.getReinforcementRatio(), 4, RoundingMode.HALF_UP))
                .multiply(new BigDecimal(1).add(new BigDecimal(2).multiply(param.getShapeFactor1()))
                        .add(BigDecimal.valueOf(0.4).multiply(param.getShapeFactor2())))).multiply(param.getResult3());
        param.setResult4(result4);

        //钢筋的平均应变
        BigDecimal result5 = (result2.subtract(param.getAverageStrain())).multiply(param.getResult3());
        param.setResult5(result5);

        //刚筋截面积 Ag
        BigDecimal result8 = new BigDecimal(Math.PI)
                .multiply(param.getDiameterOfTensileReinforcement().pow(2))
                .divide(new BigDecimal(4), 10, RoundingMode.HALF_UP);
        param.setResult8(result8.setScale(4, RoundingMode.HALF_UP));

        //og
        BigDecimal multiply = BigDecimal.valueOf(0.87).multiply(result5).multiply(param.getDistance());
        BigDecimal result9 = param.getSectionBendingMoment().divide(multiply, 4, RoundingMode.HALF_UP);
        param.setResult9(result9);

        //ofMax
        BigDecimal divide = result9.divide(param.getElasticModulus(), 10, RoundingMode.HALF_UP);
        BigDecimal result10 = BigDecimal.valueOf(2).multiply(param.getResult1()).multiply(divide).multiply(param.getResult4());


        param.setResult10(result10.setScale(4, RoundingMode.HALF_UP));

        if (PlatformObjectUtils.isEmpty(param.getResult10Correct())) {
            param.setResult10Correct(param.getResult10());
        }

        //将米转换为毫米
        BigDecimal result10mm = result10.multiply(new BigDecimal(1000));

        //破坏程度
        if (result10mm.compareTo(BigDecimal.valueOf(0.2)) < 0) {
            param.setDisasterRateState("基本完好");
        }
        if (result10mm.compareTo(BigDecimal.valueOf(0.2)) != -1 && result10mm.compareTo(BigDecimal.valueOf(0.5)) < 0) {
            param.setDisasterRateState("轻微破坏");
        }
        if (result10mm.compareTo(BigDecimal.valueOf(0.5)) != -1 && result10mm.compareTo(BigDecimal.valueOf(0.8)) < 0) {
            param.setDisasterRateState("中等破坏");
        }
        if (result10mm.compareTo(BigDecimal.valueOf(0.8)) != -1 && result10mm.compareTo(BigDecimal.valueOf(1.2)) < 0) {
            param.setDisasterRateState("严重破坏");
        }
        if (result10mm.compareTo(BigDecimal.valueOf(1.2)) > 0) {
            param.setDisasterRateState("毁坏");
        }

        if (PlatformObjectUtils.isNotEmpty(param.getResult10Correct())) {
            BigDecimal correct = param.getResult10Correct().multiply(new BigDecimal(1000));
            if (correct.compareTo(BigDecimal.valueOf(0.2)) < 0) {
                param.setDisasterRateStateCorrect("基本完好");
            }
            if (correct.compareTo(BigDecimal.valueOf(0.2)) != -1 && correct.compareTo(BigDecimal.valueOf(0.5)) < 0) {
                param.setDisasterRateStateCorrect("轻微破坏");
            }
            if (correct.compareTo(BigDecimal.valueOf(0.5)) != -1 && correct.compareTo(BigDecimal.valueOf(0.8)) < 0) {
                param.setDisasterRateStateCorrect("中等破坏");
            }
            if (correct.compareTo(BigDecimal.valueOf(0.8)) != -1 && correct.compareTo(BigDecimal.valueOf(1.2)) < 0) {
                param.setDisasterRateStateCorrect("严重破坏");
            }
            if (correct.compareTo(BigDecimal.valueOf(1.2)) > 0) {
                param.setDisasterRateStateCorrect("毁坏");
            }
        }
        param.setIds(ids.toString());
        return RestResponse.succeed(param);
    }
}
